package com.jyf.opencv

import android.Manifest
import android.content.pm.PackageManager
import android.hardware.Camera
import android.os.Build
import android.os.Bundle
import android.view.Surface
import android.view.SurfaceHolder
import android.view.SurfaceView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() ,SurfaceHolder.Callback,Camera.PreviewCallback{

    companion object {
        init {
            System.loadLibrary("native-lib")
        }
    }

    fun checkPermission(): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(arrayOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA
            ), 1)
        }
        return false
    }

    var cameraHelper: CameraHelper?=null
    val cameraId: Int = Camera.CameraInfo.CAMERA_FACING_FRONT

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val surfaceView = findViewById<SurfaceView>(R.id.surfaceView)
        checkPermission()
        surfaceView.holder.addCallback(this)
        cameraHelper = CameraHelper(cameraId)
        cameraHelper!!.setPreviewCallback(this)
        Utils.copyAssets(this, "lbpcascade_frontalface.xml")

    }

    override fun onResume() {
        super.onResume()
        init("/sdcard/lbpcascade_frontalface.xml")
        cameraHelper?.startPreview()

    }

    override fun onStop() {
        super.onStop()
        cameraHelper?.stopPreview()
    }


    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
    }

    override fun surfaceDestroyed(holder: SurfaceHolder?) {
    }

    override fun surfaceCreated(holder: SurfaceHolder?) {
//        surface-->native
//        bitmap可以和opencv的mat互转
        setSurface(holder?.surface)
    }



    override fun onPreviewFrame(data: ByteArray?, camera: Camera?) {
        postData(data,CameraHelper.WIDTH,CameraHelper.HEIGHT,cameraId)
    }

    external fun postData(data: ByteArray?, width: Int, height: Int, cameraId: Int)

    external fun init(path: String?)

    external fun setSurface(surface: Surface?)
}